<template>
  <div class="trading-controller" ref="controllerRef">
    <!-- 主控制面板 -->
    <ControllerPanel
      :active-set="activeSet"
      :font-size="fontSize"
      :has-active-panels="hasActivePanels"
      :trading-panels="tradingPanels"
      :is-sync-mode="isSyncMode"
      @set-click="handleSetClick"
      @search-click="handleSearchClick"
      @save-click="handleSaveClick"
      @hide-click="handleHideClick"
      @exit-click="handleExitClick"
      @show-all="handleShowAllClick"
      @sync-panels-click="handleSyncPanelsClick"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import ControllerPanel from "@/components/trading-controller/ControllerPanel.vue";
import { useTradingPanels } from "@/composables/trading-controller/useTradingPanels";
import { useConfigManager } from "@/composables/trading-controller/useConfigManager";
import { useXMLConfig } from "@/composables/trading-controller/useXMLConfig";
import { useAppActions } from "@/composables/trading-controller/useAppActions";

import { useContractEvents } from "@/composables/useContractEvents";
import { useMonitorManager } from "@/composables/useMonitorManager";
import { useConnectionMonitor } from "@/composables/useConnectionMonitor";
import { useConnectionNotification } from "@/composables/useConnectionNotification";
import { Window, LogicalSize } from "@tauri-apps/api/window";

// 响应式数据
const fontSize = ref(12);

// 使用组合式函数
const {
  tradingPanels,
  isSyncMode,
  hasActivePanels,
  openTradingPanel,
  hideAllTradingPanels,
  showAllTradingPanels,
  showSetPanels,
  closeAllTradingPanels,
  toggleSyncMode,
  initializeSync,
} = useTradingPanels();

const { activeSet, saveConfiguration } = useConfigManager();

const controllerRef = ref<HTMLElement>();
const windowWidth = ref(300);
const windowHeight = ref(40);

// 为useContractEvents创建包装函数
const openTradingPanelForContract = async (options: {
  setNumber: number;
  tradeName?: string;
  contractCode?: string;
  windowConfig?: any;
  priceTick?: number;
}) => {
  await openTradingPanel(options);
};

// 为useAppActions创建包装函数
const openTradingPanelForApp = async (setNumber: number, tradeName?: string) => {
  await openTradingPanel({ setNumber, tradeName });
};

// 为XML配置创建包装函数
const openTradingPanelForXML = async (
  setNumber: number,
  tradeName?: string,
  contractCode?: string,
  windowConfig?: any,
  priceTick?: number
) => {
  await openTradingPanel({
    setNumber,
    tradeName,
    contractCode,
    windowConfig,
    priceTick,
  });
};

const { autoLoadXMLConfiguration, loadXMLConfiguration } = useXMLConfig();

const { handleMenuAction } = useAppActions(
  openTradingPanelForApp,
  () => activeSet.value
);

// 初始化合约事件监听
useContractEvents(openTradingPanelForContract, () => activeSet.value);

// 初始化连接状态监控
const connectionMonitor = useConnectionMonitor();
console.log('✅ [TradingController] 连接状态监控已初始化', connectionMonitor);

// 初始化连接异常通知
const connectionNotification = useConnectionNotification();
console.log('✅ [TradingController] 连接异常通知已初始化');



// 处理交易集按钮点击
const handleSetClick = async (setNumber: number) => {
  activeSet.value = setNumber;

  // 只切换到指定的面板集，显示该集合的已有面板
  // 不创建新的默认面板，只有通过合约搜索才能添加新面板
  await showSetPanels(setNumber);
};

// 处理隐藏按钮点击
const handleHideClick = async () => {
  await hideAllTradingPanels();
};

// 处理面板空白区域点击
const handleShowAllClick = async () => {
  await showAllTradingPanels();
};

// 处理同步面板按钮点击
const handleSyncPanelsClick = async () => {
  await toggleSyncMode(activeSet.value);
};

// 处理搜索按钮点击
const handleSearchClick = async () => {
  await handleMenuAction('search', {
    saveConfiguration: () => saveConfiguration(tradingPanels.value),
    loadXMLConfiguration: () => loadXMLConfiguration(openTradingPanelForXML),
    closeAllTradingPanels,
  });
};

// 处理保存按钮点击
const handleSaveClick = async () => {
  await handleMenuAction('save', {
    saveConfiguration: () => saveConfiguration(tradingPanels.value),
    loadXMLConfiguration: () => loadXMLConfiguration(openTradingPanelForXML),
    closeAllTradingPanels,
  });
};

// 处理退出按钮点击
const handleExitClick = async () => {
  await handleMenuAction('exit', {
    saveConfiguration: () => saveConfiguration(tradingPanels.value),
    loadXMLConfiguration: () => loadXMLConfiguration(openTradingPanelForXML),
    closeAllTradingPanels,
  });
};

// 键盘事件处理
const keyboardHandler = (event: KeyboardEvent) => {
  // 简单的键盘处理逻辑
  if (event.ctrlKey && event.key >= "1" && event.key <= "5") {
    const setNumber = parseInt(event.key);
    handleSetClick(setNumber);
    event.preventDefault();
  }
};

// 动态调整窗口大小
const adjustWindowSize = async () => {
  await nextTick();

  if (controllerRef.value) {
    const rect = controllerRef.value.getBoundingClientRect();
    const contentWidth = rect.width; // 最小宽度250px，添加20px边距
    const contentHeight = rect.height; // 最小高度40px，添加10px边距

    windowWidth.value = contentWidth;
    windowHeight.value = contentHeight;

    const curWindow = Window.getCurrent();
    await curWindow.setSize(new LogicalSize(contentWidth, contentHeight));
    await curWindow.show();
  }
};

// 组件挂载
onMounted(async () => {
  document.addEventListener("keydown", keyboardHandler);

  // 初始化显示器信息（在加载配置前）
  const { initializeMonitors } = useMonitorManager();
  await initializeMonitors();

  // 自动加载默认XML配置文件
  await autoLoadXMLConfiguration(openTradingPanelForXML);

  // 初始化同步功能（在配置加载后）
  await initializeSync();

  // 初始调整窗口大小
  await adjustWindowSize();
});
</script>

<style scoped>
.trading-controller {
  /* width: 250px; */
  height: 26px;
  /* position: relative; */
  user-select: none;
  display: flex;
  max-width: fit-content;
}
</style>
